package 栈.数组模拟栈;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        // 入满再看
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.list();
        // 弹完再看
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.list();
    }
}

class ArrayStack{
     int top = -1; // 栈顶默认为-1
    private int[] stack = null;
    private int maxSize; // 栈的最大容量
    public ArrayStack(int size){
        maxSize = size;
        stack = new int[size];
    }

    public void push(int value) {
        if (top == maxSize - 1) {
            throw new RuntimeException("栈满，元素不能入栈");
        }
        stack[++top] = value;
    }

    public int pop(){
        if (top == -1) {
            throw new RuntimeException("栈空，没有元素可以出栈");
        }
        int value = stack[top--];
        return value;
    }

    public void list(){ // 遍历栈的时候不能移动top，因为出栈方法才可去移动top
        int temp = top;
        for (int i = temp; i >= 0 ; i--) {
            System.out.println(stack[temp--]);
        }
    }
}
